package com.my.cas.services;

import com.my.cas.domain.AuthorityInfo;
import com.my.cas.domain.UserInfo;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 用于加载用户信息 实现UserDetailsService接口，或者实现AuthenticationUserDetailsService接口
 */
//@Service
public class CustomUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {
    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        // 结合具体的逻辑去实现用户认证，并返回继承UserDetails的用户对象;
        System.out.println("当前的用户名是："+token.getName());

        //获取用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(token.getName());
        userInfo.setRole("ROLE_USER");
        Map<String, Object> userAttributess = token.getAssertion().getPrincipal().getAttributes();
        //System.out.println(userAttributess.toString());
        if (userAttributess != null) {
            userInfo.setId( String.valueOf(userAttributess.get("id")));
            userInfo.setNickname( String.valueOf(userAttributess.get("nickname")));
            userInfo.setRealName( String.valueOf(userAttributess.get("real_name")));
            userInfo.setEmail( String.valueOf(userAttributess.get("email")));
            userInfo.setCountryCode( String.valueOf(userAttributess.get("country_code")));
        }
        Set<AuthorityInfo> authorities = new HashSet<AuthorityInfo>();
        AuthorityInfo authorityInfo = new AuthorityInfo("TEST");
        authorities.add(authorityInfo);
        userInfo.setAuthorities(authorities);
        System.out.println(userInfo.toString());
        return userInfo;
//        System.out.println("当前的用户名是："+token.getName());
//        /*这里我为了方便，就直接返回一个用户信息，实际当中这里修改为查询数据库或者调用服务什么的来获取用户信息*/
//        UserInfo userInfo = new UserInfo();
//        userInfo.setUsername("admin");
//        Set<AuthorityInfo> authorities = new HashSet<AuthorityInfo>();
//        AuthorityInfo authorityInfo = new AuthorityInfo("TEST");
//        authorities.add(authorityInfo);
//        userInfo.setAuthorities(authorities);
//        return userInfo;

    }

}